package com.dingshi.security;

import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.PhoneStateListener;
import android.telephony.SignalStrength;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.LinearLayout;

import com.dingshi.security.SecurityApp.MessageListener;
import com.dingshi.security.api.ApiResult;
import com.dingshi.security.api.ApiReturnResultListener;
import com.dingshi.security.api.NightApi;
import com.dingshi.security.config.Config;
import com.dingshi.security.db.SettingLoader;
import com.dingshi.security.util.StringUtils;
import com.dingshi.security.util.Utils;
import com.dingshi.security.view.MainTitleView;
import com.dingshi.security.view.NightDialog;

public class BaseActivity extends Activity {

	private static final int NIGHT_DIALOG = 3000;
	LinearLayout baseLayout;
	private LayoutInflater mInflater;
	private MainTitleView titleView;
	Handler cwjHandler = new Handler();
	private Timer countDownTimer;
	private NightDialog nightDialog;
	protected boolean fromOther = false;// 是否来自夜班确认
	private int COUNTDOWN = 120;
	private static boolean isStartTime = false;
	public Handler mHandler;
	private Thread mClockThread;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		this.getWindow().addFlags(
				WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		super.setContentView(R.layout.base);
		SecurityApp.allActivity.add(this);
		baseLayout = (LinearLayout) findViewById(R.id.baseView);
		// timeStart();

		titleView = (MainTitleView) findViewById(R.id.thisTitle);

		batteryLevel();
		signalStart();
		titleView.setAttendant(SettingLoader.getGuardName(this));
		titleView.setesidential(SettingLoader.getAreaName(this));

		handleMsg();
	}

	@Override
	protected void onPause() {
		mClockThread.interrupt();
		mClockThread = null;
		mHandler = null;
		super.onPause();
	}

	@Override
	protected void onResume() {
		refreshTime();
		mHandler = new Handler() {
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case 0: {
					refreshTime();
				}
					break;
				}
				super.handleMessage(msg);
			}
		};

		mClockThread = new LooperThread();
		mClockThread.start();
		super.onResume();
	}

	public void setContentView(int resId) {
		mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		ViewGroup mBarView = (ViewGroup) mInflater.inflate(resId, null);

		baseLayout.addView(mBarView);
	}

	public void refreshTime() {
		Calendar ca = Calendar.getInstance();
		final int year = ca.get(Calendar.YEAR);// 获取年份
		final int month = ca.get(Calendar.MONTH);// 获取月份
		final int day = ca.get(Calendar.DATE);// 获取日
		final int minute = ca.get(Calendar.MINUTE);// 分
		final int hour = ca.get(Calendar.HOUR);// 小时
		final int second = ca.get(Calendar.SECOND);// 秒
		final int WeekOfYear = ca.get(Calendar.DAY_OF_WEEK);
		final int amOrPm = ca.get(Calendar.AM_PM);
		titleView.clock_am_panel.setText(amOrPm == 0 ? "上午" : "下午");

		titleView.clock_time_panel.setText((hour < 10 ? "0" + hour : hour)
				+ ":" + (minute < 10 ? "0" + minute : minute));

	}

	class LooperThread extends Thread {
		public void run() {
			super.run();
			try {
				do {
					Thread.sleep(1000);
					Message m = new Message();
					m.what = 0;
					mHandler.sendMessage(m);
				} while (mClockThread.interrupted() == false);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public void onAttachedToWindow() {
		this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
		super.onAttachedToWindow();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_HOME:
			Log.e("KeyCode", "home is click");
			return true;
		case KeyEvent.KEYCODE_BACK:

			return true;
		case KeyEvent.KEYCODE_DPAD_LEFT: {
			return true;
		}

		case KeyEvent.KEYCODE_DPAD_UP: {
			return true;
		}

		case KeyEvent.KEYCODE_DPAD_RIGHT: {
			return true;
		}

		case KeyEvent.KEYCODE_DPAD_DOWN: {
			return true;
		}
		case KeyEvent.KEYCODE_DPAD_CENTER: {
			return true;
		}
		default:
			break;
		}
		return super.onKeyDown(keyCode, event);
	}

	/**
	 * 夜班确认
	 */
	private void handleMsg() {
		fromOther = getIntent().getBooleanExtra("from", false);
		SecurityApp.getApp(this).setMessageListener(new MessageListener() {

			@Override
			public void messageCallBack(Message msg) {
				if (1 == msg.arg1) {
					runOnUiThread(new Runnable() {

						@Override
						public void run() {
							if (!fromOther) {
								showNightDialog();
							}
						}
					});

				}
			}
		});

	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case NIGHT_DIALOG:
			nightDialog = new NightDialog(this,
					new NightDialog.OnButtonClickListener() {

						@Override
						public void onOkButtonClicked(NightDialog dialog) {
							nightShiftConfirm(1, null, dialog);
						}

						@Override
						public void onCancleButtonClicked(NightDialog dialog) {
							Intent intent = new Intent(BaseActivity.this,
									RepairCreateActivity.class);
							intent.putExtra("from", true);
							startActivityForResult(intent, 1);
						}
					});
			return nightDialog;

		default:
			break;
		}
		return super.onCreateDialog(id);
	}

	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		super.onPrepareDialog(id, dialog);
	};

	private void showNightDialog() {
		if ("2".equals(SettingLoader.getLoginUserType(this))) {
			if (!isFinishing()) {
				showDialog(NIGHT_DIALOG);
			}

			if (countDownTimer != null) {
				countDownTimer.cancel();
				countDownTimer = null;
			}
			countDownTimer = new Timer();
			countDownTimer.schedule(new TimerTask() {
				@Override
				public void run() {
					runOnUiThread(new Runnable() {

						@Override
						public void run() {
							Log.e("Timer", "开始倒计时");
							if (COUNTDOWN >= 0) {
								if (nightDialog != null) {
									nightDialog.getCountDown().setText(
											"倒计时：" + COUNTDOWN);
								}
								COUNTDOWN--;
							} else {
								COUNTDOWN = Config.COUNTDOWN;
								nightShiftConfirm(3, null, nightDialog);
							}
						}

					});
				}
			}, 0, 1000);
		}
	}

	public Timer timetask;

	public void timeStop() {
		if (timetask != null) {
			timetask.cancel();
			timetask = null;
		}
	}

	public void timeStart() {

		if (!isStartTime) {
			timetask = new Timer();
			timetask.schedule(new TimerTask() {

				@Override
				public void run() {

					Calendar ca = Calendar.getInstance();
					final int year = ca.get(Calendar.YEAR);// 获取年份
					final int month = ca.get(Calendar.MONTH);// 获取月份
					final int day = ca.get(Calendar.DATE);// 获取日
					final int minute = ca.get(Calendar.MINUTE);// 分
					final int hour = ca.get(Calendar.HOUR);// 小时
					final int second = ca.get(Calendar.SECOND);// 秒
					final int WeekOfYear = ca.get(Calendar.DAY_OF_WEEK);
					final int amOrPm = ca.get(Calendar.AM_PM);

					cwjHandler.post(new Runnable() {

						@Override
						public void run() {

							titleView.clock_am_panel.setText(amOrPm == 0 ? "上午"
									: "下午");

							titleView.clock_time_panel.setText((hour < 10 ? "0"
									+ hour : hour)
									+ ":"
									+ (minute < 10 ? "0" + minute : minute));
							Log.e("titleView", (hour < 10 ? "0" + hour : hour)
									+ ":"
									+ (minute < 10 ? "0" + minute : minute)
									+ ":"
									+ (second < 10 ? "0" + second : second));
						}
					});

				}
			}, 1000, 1000);
			isStartTime = true;
		}
	}

	@Override
	protected void onStop() {
		if (countDownTimer != null) {
			countDownTimer.cancel();
			countDownTimer = null;
		}
		super.onStop();
	}

	BroadcastReceiver batteryLevelReceiver;

	private void batteryLevel() {
		batteryLevelReceiver = new BroadcastReceiver() {
			public void onReceive(Context context, Intent intent) {
				context.unregisterReceiver(this);
				int rawlevel = intent.getIntExtra("level", -1);// 获得当前电量
				int scale = intent.getIntExtra("scale", -1);

				// 获得总电量
				int level = -1;
				if (rawlevel >= 0 && scale > 0) {
					level = (rawlevel * 100) / scale;
				}
				titleView.setBaatery(level);
			}
		};
		IntentFilter batteryLevelFilter = new IntentFilter(
				Intent.ACTION_BATTERY_CHANGED);
		getApplication().getApplicationContext().registerReceiver(
				batteryLevelReceiver, batteryLevelFilter);
	}

	TelephonyManager Tel;
	MyPhoneStateListener MyListener;

	public void signalStart() {
		MyListener = new MyPhoneStateListener();
		Tel = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
		Tel.listen(MyListener, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
	}

	private class MyPhoneStateListener extends PhoneStateListener {
		/* 得到信号的强度由每个tiome供应商,有更新 */
		@Override
		public void onSignalStrengthsChanged(SignalStrength signalStrength) {
			super.onSignalStrengthsChanged(signalStrength);
			titleView.setSignal(signalStrength.getGsmSignalStrength());
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (RESULT_OK == resultCode) {
			if (1 == requestCode) {
				String diaryNum = data.getStringExtra("diaryNum");
				nightShiftConfirm(2, diaryNum, nightDialog);
				fromOther = false;
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	/**
	 * type 夜班确认情况 1 正常 2不正常 3 未确认
	 * 
	 * @param i
	 */
	private void nightShiftConfirm(int type, String diaryNum, NightDialog dialog) {
		if (dialog != null && dialog.isShowing()) {
			dialog.dismiss();
		}
		if (countDownTimer != null) {
			countDownTimer.cancel();
			countDownTimer = null;
		}
		NightApi api = new NightApi(this);
		switch (type) {
		case 1:
			api.reportNightShift(1, this, SettingLoader.getDepartNum(this),
					SettingLoader.getAreaNum(this),
					SettingLoader.getGuardNum(this), "1", null);
			break;
		case 2:
			api.reportNightShift(1, this, SettingLoader.getDepartNum(this),
					SettingLoader.getAreaNum(this),
					SettingLoader.getGuardNum(this), "2", diaryNum);
			break;
		case 3:
			api.reportNightShift(1, this, SettingLoader.getDepartNum(this),
					SettingLoader.getAreaNum(this),
					SettingLoader.getGuardNum(this), "3", null);
			break;

		default:
			break;
		}
		api.setReturnResultListener(new ApiReturnResultListener() {

			@Override
			public <T> void onReturnSucceedResult(int requestCode,
					ApiResult<T> apiResult) {
				JSONObject jsonEntity = apiResult.getJsonEntity();
				Log.e("aa", jsonEntity.toString());
				if (jsonEntity != null) {
					// {"d":{"__type":"OperatorReturn:r","r":"2"},"t":1}

					try {
						int type = jsonEntity.getInt("t");
						switch (type) {
						case 0:// 对象
							JSONObject json = jsonEntity.getJSONObject("d");
							String result = json.getString("r");
							if (!StringUtils.isNullOrEmpty(result)
									&& 0 < Integer.parseInt(result)) {
								Utils.showToast(BaseActivity.this, "确认成功");
							} else {
								Utils.showToast(BaseActivity.this, "确认失败");
							}
							break;
						case 1:// 数组

							break;
						case -1:// 错误
							Utils.showToast(BaseActivity.this, "添加失败");
							break;

						default:
							break;
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}

			}

			@Override
			public <T> void onReturnLoading(int requestCode) {
				// TODO Auto-generated method stub

			}

			@Override
			public <T> void onReturnFailResult(int requestCode,
					ApiResult<T> apiResult) {
				// TODO Auto-generated method stub

			}
		});
	}

}